/**
 * 与审核相关的组件，存于这里
 */
import {
  Avatar,
  Button,
  Checkbox,
  Collapse,
  Divider,
  DotLoading,
  Form,
  Grid,
  Input,
  NoticeBar,
  Popup,
  Result,
  Space,
  Steps,
  Tag,
  Toast,
} from 'antd-mobile';
import React, { FC, useEffect, useState } from 'react';
// import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
// import { Content, Page } from '@alita/flow';
import { DemoBlock } from '@/components/demos-util';
import { WeiXinUser, type DetailResult } from '@/pages/types/type';
import dayjs from 'dayjs';
// import type { DatePickerRef } from 'antd-mobile/es/components/date-picker'

import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
// import { CascaderOption } from 'antd-mobile/es/components/cascader-view';
import { SHORT_DATE_TIME_FORMAT } from '@/constants';
import {
  AntOutline,
  CheckCircleFill,
  CheckCircleOutline,
  ClockCircleOutline,
  CloseShieldOutline,
  FlagOutline,
  HandPayCircleOutline,
  MinusCircleOutline,
  QuestionCircleOutline,
  TagOutline,
} from 'antd-mobile-icons';
import { ColorString } from 'echarts/types/src/util/types.js';
import styles from './index.less';

const { Step } = Steps;

interface AuditPointDef {
  id: number;
  createdAt: string;
  round: { id: number; createdAt: string; isLast: boolean };
  node: {
    id: number;
    name: string;
    fullName: string;
    isRoot: boolean;
    isLeaf: boolean;
    roundId: number;
    grouped: boolean;
    level: string;
    leader: WeiXinUser;
  };
  livings: {
    id: number;
    standard: { value: string; label: string };
    remark: string;
    start: string;
    createdAt: string;
  }[];
  children: AuditPointDef[];
}

const AuditTalkNodeIcon: FC<{ auditStatus: any }> = ({ auditStatus }) => {
  const {
    launched,
    notArrived,
    incomingX,
    approve,
    remanded,
    terminated,
    waitingX,
    needYouX,
    audited,
  } = auditStatus;
  if (notArrived) {
    return <ClockCircleOutline />;
  }

  if (launched) {
    return <TagOutline color={`var(--adm-color-primary)`} />;
  }
  if (incomingX) {
    return <AntOutline color={`var(--adm-color-warning)`} />;
  }
  if (approve) {
    return <CheckCircleOutline color="var(--adm-color-primary)" />;
  }
  if (waitingX) {
    return <ClockCircleOutline color={`var(--adm-color-warning)`} />;
  }
  if (needYouX) {
    return <QuestionCircleOutline color={`var(--adm-color-warning)`} />;
  }
  if (remanded) {
    return <CloseShieldOutline color="var(--adm-color-danger)" />;
  }

  if (terminated) {
    return <MinusCircleOutline color="var(--adm-color-danger)" />;
  }

  if (audited) {
    return <CheckCircleFill color="var(--adm-color-success)" />;
  }

  return <HandPayCircleOutline />;
};

const ReplyPopup: FC<{
  url: string;
  shortUrl: string;
  point: number;
  onSuccess: () => void;
  buttonText: string;
}> = ({ buttonText, url, shortUrl, point, onSuccess }) => {
  const [ing, setIng] = useState<boolean>(false);
  const [success, setSuccess] = useState<string>();
  const [fail, setFail] = useState<string>();
  const [visible, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState(true);
  const [loadFail, setLoadFail] = useState<string>();
  const [loadSuccess, setLoadSuccess] = useState<string>();
  const [canDo, setCanDo] = useState<boolean>(true);

  // function load() {
  //   setLoading(true);
  //   setLoadFail(undefined);
  //   setLoadSuccess(undefined);
  //   let response: Promise<Response> = fetch( `${urlPrefix}${url}/${shortUrl}/${point}`,  getRequestInit(), );
  //   response
  //     .then((rsp: Response) => {
  //       // console.log(rsp);
  //       if (rsp.ok) {
  //         rsp
  //           .json()
  //           .then(({ data, code, msg }: DetailResult<boolean>) => {
  //             if (code === 0) {
  //               setCanDo(data!);
  //               setLoadSuccess(msg);
  //             } else {
  //               setLoadFail(msg);
  //             }
  //           })
  //           .catch((reason) => {
  //             setLoadFail(reason);
  //           });
  //       }
  //     })
  //     .catch((reason: any) => {
  //       console.error(reason);
  //       setLoadFail(`发生错误：${reason}`);
  //     })
  //     .finally(() => {
  //       setLoading(false);
  //     });
  // }
  // useEffect(load, [url, shortUrl,point]);

  async function onFinish(values: { remark: string }) {
    setIng(true);
    setFail(undefined);
    setSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}${url}/${shortUrl}/${point}`,
      postRequestInit(values),
    );
    response
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then((x: DetailResult<number>) => {
              const { data, code, msg } = x;
              console.log('new living=', data);
              if (code === 0) {
                setSuccess(msg);
                setVisible(false);
                onSuccess();
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setIng(false);
      });
  }

  return (
    <React.Fragment>
      <Button
        type={'button'}
        shape="rounded"
        size="mini"
        color="primary"
        disabled={!canDo}
        onClick={() => setVisible(true)}
      >
        {buttonText}
      </Button>
      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        destroyOnClose
      >
        <DemoBlock padding={8} title={buttonText}>
          <Form
            layout={'vertical'}
            onFinish={onFinish}
            footer={
              <>
                {fail !== undefined && (
                  <Result
                    status="error"
                    title="无法完成操作"
                    description={
                      <>
                        {fail}
                        <Divider />
                        <Button size="mini" onClick={() => setFail(undefined)}>
                          再试一次
                        </Button>
                      </>
                    }
                  />
                )}
                <Button
                  block
                  type="submit"
                  disabled={ing || fail !== undefined || success !== undefined}
                  loading={ing}
                  color="primary"
                  size="large"
                >
                  {success !== undefined
                    ? `已回复${buttonText}`
                    : fail !== undefined
                      ? '执行失败'
                      : buttonText}
                </Button>
              </>
            }
          >
            <Form.Item
              name="message"
              label="备注"
              rules={[{ required: true, message: '备注' }]}
            >
              <Input placeholder="备注" maxLength={200} />
            </Form.Item>
          </Form>
        </DemoBlock>
      </Popup>
    </React.Fragment>
  );
};

const AuditPointList: FC<{
  points: AuditNodePoint[];
  url: string;
  onSuccess: () => void;
}> = ({ points, url, onSuccess }) => {
  return (
    <Steps direction="vertical" current={-1}>
      {points.map(
        (
          { id, children, livings, canDoActionX, node, lockedTime, isRoot },
          index,
        ) => {
          const tips = [
            { key: 'needFeedback', shortUrl: 'provide-feedback', text: '回复' },
            {
              key: 'needModify',
              shortUrl: 'modify-completed',
              text: '反馈修改情况',
            },
            {
              key: 'waitingFeedbackAgain',
              shortUrl: 'waiting-for-feedback-by-reply',
              text: '再次问询',
            },
            {
              key: 'waitingModifyAgain',
              shortUrl: 'waiting-for-modification-by-reply',
              text: '再次要求修改',
            },
          ];
          const a_need = livings[0].standard.value === 'needYouModify';
          const b_need = livings[0].standard.value === 'needYouFeedback';
          const need = a_need || b_need;
          const tk = tips.findIndex((t) => t.key === canDoActionX);

          return (
            <Step
              key={index}
              title={
                <>
                  {!need && (
                    <>
                      {!isRoot && (
                        <>
                          <u>{node.leader.name}</u>
                        </>
                      )}{' '}
                      :{livings[0].remark}
                    </>
                  )}
                  {tk < 0 && a_need && (
                    <>待申请人{node.leader.name}修改并反馈</>
                  )}
                  {tk < 0 && b_need && <>待{node.leader.name}回复</>}
                  {tk >= 0 && !lockedTime && (
                    <ReplyPopup
                      buttonText={tips[tk].text}
                      shortUrl={tips[tk].shortUrl}
                      url={url}
                      onSuccess={onSuccess}
                      point={id}
                    />
                  )}
                </>
              }
              description={
                children.length > 0 && (
                  <>
                    <Grid columns={1} gap={8}>
                      <Grid.Item>
                        <AuditPointList
                          onSuccess={onSuccess}
                          url={url}
                          points={children}
                        />
                      </Grid.Item>
                    </Grid>
                  </>
                )
              }
            />
          );
        },
      )}
    </Steps>
  );
};

export const AuditTalkNodes: FC<{
  nodes: AuditNode[];
  url: string;
  origin: string | number;
  onSuccess: () => void;
}> = ({ nodes, url, origin, onSuccess }) => {
  return (
    <Steps direction="vertical" current={-1}>
      {nodes.map((node, index: number) => {
        const {
          children,
          auditStatuses,
          leader,
          grouped,
          level,
          points,
          lightingAt,
          decidedAt,
        } = node;

        const onePointNoneChildren =
          points.length === 1 && points[0].children.length < 1;
        return (
          <Step
            key={index}
            icon={
              grouped ? (
                <AuditTalkNodeIcon auditStatus={auditStatuses[0]} />
              ) : level === 'end' ? (
                <FlagOutline />
              ) : (
                <Avatar
                  src={leader?.thumbAvatar}
                  style={{ '--size': '28px' }}
                />
              )
            }
            title={
              <>
                <Grid columns={1} gap={8}>
                  <Grid.Item>
                    {node.name} {leader && level !== 'end' && leader.name}
                  </Grid.Item>
                </Grid>
                {decidedAt && !grouped && (
                  <Grid columns={1} gap={8}>
                    <Grid.Item>
                      {dayjs(decidedAt).format(SHORT_DATE_TIME_FORMAT)}
                    </Grid.Item>
                  </Grid>
                )}

                {!grouped &&
                  auditStatuses.map((auditStatuse, index) => (
                    <Grid key={index} columns={1} gap={8}>
                      <AuditTalkNodeIcon auditStatus={auditStatuse} />
                    </Grid>
                  ))}
                {onePointNoneChildren && (
                  <Grid columns={1} gap={8}>
                    <Grid.Item>{points[0].livings[0].remark}</Grid.Item>
                  </Grid>
                )}

                {points.length >= 1 && !onePointNoneChildren && (
                  <Grid columns={1} gap={8}>
                    <Grid.Item>
                      <AuditPointList
                        url={url}
                        onSuccess={onSuccess}
                        points={points}
                      />
                    </Grid.Item>
                  </Grid>
                )}
              </>
            }
            description={
              <>
                {children && children.length > 0 && (
                  <Grid columns={1} gap={8}>
                    <Grid.Item>
                      <AuditTalkNodes
                        onSuccess={onSuccess}
                        nodes={children}
                        url={url}
                        origin={origin}
                      />
                    </Grid.Item>
                  </Grid>
                )}
              </>
            }
          />
        );
      })}
    </Steps>
  );
};

const DecideTalkPopup: FC<{
  url: string;
  origin: number | string;
  buttonText?: string;
  color?: 'success' | 'default' | 'primary' | 'warning' | 'danger';
  targetUrl?: string;
  initialValue?: string;
  label?: string;
  onSuccess: () => void;
}> = ({
  url,
  origin,
  onSuccess,
  buttonText = '通过',
  color = 'primary',
  initialValue = '通过',
  label = '意见',
  targetUrl = 'approve',
}) => {
    const [visible, setVisible] = useState<boolean>(false);
    const [ing, setIng] = useState<boolean>(false);
    const [success, setSuccess] = useState<string>();
    const [fail, setFail] = useState<string>();
    const [loading, setLoading] = useState(true);
    const [loadFail, setLoadFail] = useState<string>();
    const [loadSuccess, setLoadSuccess] = useState<string>();
    const [canDo, setCanDo] = useState<boolean>(true);
    async function onFinish(values: { remark: string }) {
      setIng(true);
      setFail(undefined);
      setSuccess(undefined);
      let response: Promise<Response> = fetch(
        `${urlPrefix}${url}/${targetUrl}/${origin}`,
        postRequestInit(values),
      );
      response
        .then((rsp: Response) => {
          if (rsp.ok) {
            rsp
              .json()
              .then((x: DetailResult<string[]>) => {
                console.log(x);
                const { data, code, msg } = x;
                console.log('new living=', data);
                if (code === 0) {
                  setSuccess(msg);
                  setVisible(false);
                  onSuccess();
                } else {
                  Toast.show({ icon: 'fail', content: data && data.length > 0 ? data!.join(';') : msg });
                  setFail(msg);
                }
              })
              .catch((reason) => {
                setFail(reason);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setFail(`发生错误：${reason}`);
        })
        .finally(() => {
          setIng(false);
        });
    }

    return (
      <React.Fragment>
        <Button
          type={'button'}
          shape="rounded"
          size="small"
          color={color}
          disabled={!canDo}
          block
          onClick={() => setVisible(true)}
        >
          {buttonText}
        </Button>
        <Popup
          visible={visible}
          onMaskClick={() => {
            setVisible(false);
          }}
          destroyOnClose
        >
          <DemoBlock padding={8} title={buttonText}>
            <Form
              layout={'vertical'}
              onFinish={onFinish}
              footer={
                <>
                  {fail !== undefined && (
                    <NoticeBar
                      extra={
                        <Space style={{ '--gap': '12px' }}>
                          {' '}
                          <span onClick={() => setFail(undefined)}>
                            再试一次
                          </span>{' '}
                        </Space>
                      }
                      content={fail}
                      color="alert"
                    />
                  )}
                  <Button
                    block
                    type="submit"
                    disabled={ing || fail !== undefined || success !== undefined}
                    loading={ing}
                    color={color}
                    size="large"
                  >
                    {success !== undefined
                      ? `已${buttonText}`
                      : fail !== undefined
                        ? '执行失败'
                        : buttonText}
                  </Button>
                </>
              }
            >
              <Form.Item
                name="message"
                label={label}
                initialValue={initialValue}
                rules={[{ required: true, message: '意见' }]}
              >
                <Input placeholder="备注" />
              </Form.Item>
            </Form>
          </DemoBlock>
        </Popup>
      </React.Fragment>
    );
  };

const WaitingForFeedbackTalkPopup: FC<{
  url: string;
  origin: number | string;
  onSuccess: () => void;
}> = ({ url, origin, onSuccess }) => {
  interface NoticeNode {
    id: number;
    fullName: string;
    leader: WeiXinUser;
    disabled: boolean;
  }
  const [ing, setIng] = useState<boolean>(false);
  const [loadSuccess, setLoadSuccess] = useState<string>();
  const [success, setSuccess] = useState<string>();
  const [fail, setFail] = useState<string>();
  const [visible, setVisible] = useState<boolean>(false);
  const [nodes, setNodes] = useState<NoticeNode[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadFail, setLoadFail] = useState<string>();

  function load() {
    setLoading(true);
    setLoadFail(undefined);
    setLoadSuccess(undefined);

    let response: Promise<Response> = fetch(
      `${urlPrefix}${url}/get-notice-nodes/${origin}`,
      getRequestInit(),
    );
    response
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(({ data, code, msg }: DetailResult<NoticeNode[]>) => {
              if (code === 0) {
                setNodes(data!);
              } else {
                setLoadFail(msg);
              }
            })
            .catch((reason) => {
              setLoadFail(reason);
            });
        } else {
          setLoadFail('出错！请联系管理员，错误代码：3541027841');
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }
  useEffect(load, [url, origin]);

  async function onFinish(values: { remark: string }) {
    setIng(true);
    setFail(undefined);
    setSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}${url}/waiting-for-feedback/${origin}`,
      postRequestInit(values),
    );
    response
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then((x: DetailResult<number>) => {
              console.log(x);
              const { data, code, msg } = x;
              console.log('new living=', data);
              if (code === 0) {
                setSuccess(msg);
                setVisible(false);
                onSuccess();
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setIng(false);
      });
  }

  return (
    <React.Fragment>
      <Button
        type={'button'}
        shape="rounded"
        size="small"
        block
        color={'success'}
        onClick={() => setVisible(true)}
      >
        待定
      </Button>
      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        destroyOnClose
      >
        <DemoBlock padding={8} title={`待定`}>
          <Form
            layout={'vertical'}
            onFinish={onFinish}
            footer={
              <>
                {fail !== undefined && (
                  <NoticeBar
                    extra={
                      <Space style={{ '--gap': '12px' }}>
                        {' '}
                        <span onClick={() => setFail(undefined)}>
                          再试一次
                        </span>{' '}
                      </Space>
                    }
                    content={fail}
                    color="alert"
                  />
                )}
                <Button
                  block
                  type="submit"
                  disabled={ing || fail !== undefined || success !== undefined}
                  loading={ing}
                  color="primary"
                  size="large"
                >
                  {success !== undefined
                    ? '已提交'
                    : fail !== undefined
                      ? '执行失败'
                      : '提交'}
                </Button>
              </>
            }
          >
            <Form.Item name="nodeIds" label="通知" required>
              <Checkbox.Group>
                <Space direction="vertical">
                  {nodes.map(({ id, fullName, disabled, leader: { name } }) => (
                    <Checkbox disabled={disabled} key={id} value={id}>
                      {name}({fullName})
                    </Checkbox>
                  ))}
                </Space>
              </Checkbox.Group>
            </Form.Item>
            <Form.Item
              name="message"
              label="问题"
              rules={[{ required: true, message: '备注' }]}
            >
              <Input placeholder="备注" />
            </Form.Item>
          </Form>
        </DemoBlock>
      </Popup>
    </React.Fragment>
  );
};

export const WaitingForModificationTalkPopup: FC<{
  url: string;
  origin: number | string;
  onSuccess: () => void;
}> = ({ url, origin, onSuccess }) => {
  const [ing, setIng] = useState<boolean>(false);
  const [success, setSuccess] = useState<string>();
  const [fail, setFail] = useState<string>();
  const [visible, setVisible] = useState<boolean>(false);

  async function onFinish(values: { remark: string }) {
    setIng(true);
    setFail(undefined);
    setSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}${url}/waiting-for-modification/${origin}`,
      postRequestInit(values),
    );
    response
      .then((rsp: Response) => {
        // console.log(rsp);
        if (rsp.ok) {
          rsp
            .json()
            .then((x: DetailResult<number>) => {
              // console.log(x);
              const { data, code, msg } = x;
              console.log('new living=', data);
              if (code === 0) {
                setSuccess(msg);
                setVisible(false);
                onSuccess();
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setIng(false);
      });
  }

  return (
    <React.Fragment>
      <Button
        type={'button'}
        shape="rounded"
        size="small"
        color={'warning'}
        block
        onClick={() => setVisible(true)}
      >
        要求修改
      </Button>
      <Popup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        destroyOnClose
      >
        <DemoBlock padding={8} title={`要求修改`}>
          <Form
            layout={'vertical'}
            onFinish={onFinish}
            footer={
              <>
                {fail !== undefined && (
                  <Result
                    status="error"
                    title="无法完成操作"
                    description={
                      <>
                        {fail}
                        <Divider />
                        <Button size="mini" onClick={() => setFail(undefined)}>
                          再试一次
                        </Button>
                      </>
                    }
                  />
                )}
                <Button
                  block
                  type="submit"
                  disabled={ing || fail !== undefined || success !== undefined}
                  loading={ing}
                  color="primary"
                  size="large"
                >
                  {success !== undefined
                    ? '已提交'
                    : fail !== undefined
                      ? '执行失败'
                      : '提交'}
                </Button>
              </>
            }
          >
            <Form.Item
              name="message"
              label="备注"
              rules={[{ required: true, message: '备注' }]}
            >
              <Input placeholder="备注" />
            </Form.Item>
          </Form>
        </DemoBlock>
      </Popup>
    </React.Fragment>
  );
};

declare type AuditNodePoint = {
  canDoActionX: string;
  lockedTime: string;
  children: AuditNodePoint[];
  createdAt: string;
  id: number;
  isLeaf: boolean;
  isRoot: boolean;
  node: {
    fullName: string;
    grouped: boolean;
    id: number;
    isLeaf: boolean;
    isRoot: boolean;
    leader: WeiXinUser;
    level: string;
    name: string;
    roundId: number;
  };
  round: { createdAt: string; id: number; isLast: boolean };
  livings: {
    createdAt: string;
    id: number;
    remark: string;
    standard: { label: string; value: string };
    start: string;
  }[];
};

declare type AuditNode = {
  auditStatuses: {
    approve: boolean;
    audited: boolean;
    incomingX: boolean;
    launched: boolean;
    needYouX: boolean;
    notArrived: boolean;
    remanded: boolean;
    start: string;
    terminated: boolean;
    waitingX: boolean;
  }[];

  lightingAt?: string;
  decidedAt?: string;

  children: AuditNode[];
  currentUserLeading: boolean;
  fullName: string;
  grouped: boolean;
  id: number;
  isLeaf: boolean;
  isRoot: boolean;
  leader: WeiXinUser;
  level: string;
  name: string;
  roundId: number;
  points: AuditNodePoint[];
};

declare type AuditRound = {
  createdAt: string;
  id: number;
  last: boolean;
  name: string;
  nodes: AuditNode[];
};

export const AuditRoundsMap: FC<{ url: string; origin: number | string }> = ({
  url,
  origin,
}) => {
  const [rounds, setRounds] = useState<AuditRound[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadFail, setLoadFail] = useState<string>();
  const [success, setSuccess] = useState<string>();

  function check(node: AuditNode) {
    const { currentUserLeading, auditStatuses } = node;
    return (
      (currentUserLeading && auditStatuses.some((s) => s.incomingX)) ||
      node.children.some(check)
    );
  }

  function load() {
    setLoading(true);
    setLoadFail(undefined);
    setSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}${url}/get-rounds/${origin}`,
      getRequestInit(),
    );
    response
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(({ data, code, msg }: DetailResult<AuditRound[]>) => {
              if (code === 0) {
                setRounds(data!);
                setSuccess(msg);
              } else {
                setLoadFail(msg);
              }
            })
            .catch((reason) => {
              setLoadFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }
  useEffect(load, [url, origin]);

  if (loading) {
    return <DotLoading color="primary" />;
  }
  if (rounds.length < 1) {
    return (
      <DemoBlock padding={8} marginTop={'10px'} title={`新审核过程`}>
        <Grid columns={1} gap={8}>
          <Grid.Item>无审核节点信息</Grid.Item>
        </Grid>
      </DemoBlock>
    );
  }

  // 判断当前用户是否需要审核或重启审核，注意，提供反馈或执行修改后完成后的返回，在树型内部搞，不在外面进行判断。
  const lastRound = rounds[rounds.length - 1];

  const ndoes: AuditNode[] = [...lastRound.nodes];
  const auditing = ndoes.some(check);
  const neddRestart = ndoes.some((node: AuditNode) => {
    const { currentUserLeading, auditStatuses } = node;
    return currentUserLeading && auditStatuses.some((s) => s.needYouX);
  });

  return (
    <div className={styles.AuditRoundsMap}>
      {rounds.length > 1 && (
        <DemoBlock padding={8} marginTop={'10px'}>
          <Grid columns={1} gap={8}>
            <Grid.Item>
              <Collapse accordion>
                {rounds.slice(0, -1).map((round, index) => {
                  return (
                    <Collapse.Panel
                      key={index + ''}
                      title={`第${index + 1}轮审核`}
                    >
                      <AuditTalkNodes
                        onSuccess={load}
                        nodes={round.nodes}
                        url={url}
                        origin={origin}
                      />
                    </Collapse.Panel>
                  );
                })}
              </Collapse>
            </Grid.Item>
          </Grid>
        </DemoBlock>
      )}

      {/*最后一轮审核，就是当前审核轮数！ */}
      <DemoBlock padding={8} marginTop={'10px'}>
        <Grid columns={1} gap={8}>
          <Grid.Item>
            <AuditTalkNodes
              onSuccess={load}
              nodes={lastRound.nodes}
              url={url}
              origin={origin}
            />{' '}
          </Grid.Item>
        </Grid>
      </DemoBlock>

      {auditing && (
        <DemoBlock padding={8} marginTop={'10px'}>
          <Grid columns={2} gap={8}>
            <Grid.Item>
              <DecideTalkPopup
                url={url}
                onSuccess={load}
                origin={origin}
                targetUrl="remanded"
                initialValue={'数据有问题。'}
                color={'danger'}
                label="原因"
                buttonText="发回重审"
              />
            </Grid.Item>
            <Grid.Item>
              <DecideTalkPopup url={url} onSuccess={load} origin={origin} />
            </Grid.Item>
            <Grid.Item>
              <WaitingForFeedbackTalkPopup
                onSuccess={load}
                url={url}
                origin={origin}
              />
            </Grid.Item>
            <Grid.Item>
              <WaitingForModificationTalkPopup
                onSuccess={load}
                url={url}
                origin={origin}
              />
            </Grid.Item>
          </Grid>
        </DemoBlock>
      )}

      {neddRestart && (
        <DemoBlock padding={8} marginTop={'10px'}>
          <Grid columns={1} gap={8}>
            <Grid.Item>
              <DecideTalkPopup
                url={url}
                onSuccess={load}
                origin={origin}
                targetUrl="restart"
                initialValue={'已完成修改。'}
                color={'primary'}
                label="情况说明"
                buttonText="重启审核"
              />
            </Grid.Item>
          </Grid>
        </DemoBlock>
      )}
    </div>
  );
};

export const AuditTalkStautsTip: FC<{
  url: string;
  origin: string | number;
}> = ({ url, origin }) => {
  interface TipDef {
    description: string;
    error: boolean;
    needYouRestart: boolean;
    audited: boolean;
    auditing: boolean;
  }
  const [loading, setLoading] = useState(true);
  const [loadFail, setLoadFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  const [tip, setTip] = useState<TipDef>();

  function load() {
    setLoading(true);
    setLoadFail(undefined);
    setSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}${url}/get-origin-audit-simple-status/${origin}`,
      getRequestInit(),
    );
    response
      .then((rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(({ data, code, msg }: DetailResult<TipDef>) => {
              if (code === 0) {
                setTip(data!);
                setSuccess(msg);
              } else {
                setLoadFail(msg);
              }
            })
            .catch((reason) => {
              setLoadFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }
  useEffect(load, [url, origin]);

  if (loading) {
    return <DotLoading color="primary" />;
  }

  return <Tag round> {tip?.description}</Tag>;
};
